package top.ddandang.blog.utils;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import top.ddandang.blog.bean.OssBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 阿里云Oss 工具类
 * </p>
 *
 * @author D
 * @version 1.0
 * @date 2020/6/30 11:35
 */
@Slf4j
@Component
public class OssUtil {

    @Resource
    private OssBean ossBean;

    /**
     *创建实例
     * @return OSS 实例
     */
    private OSS getClient(){
        OSS client = new OSSClientBuilder().build(ossBean.getEndpoint(),ossBean.getAccessKeyId(),ossBean.getAccessKeySecret());
        if(client==null){
            System.out.println("错误");
        }
        return client;
    }

    /**
     *  上传图片
     * @param file 图片信息
     * @param path 图片存的路径 默认在 blog 文件夹
     * @return 图片链接地址
     */
    public String uploadImage(MultipartFile file, String path) {

        //获取实例
        OSS client = getClient();
        PutObjectRequest putObjectRequest = null;

        String fileName = path+ IdUtil.simpleUUID() + ".png";
        //图片地址
        String imagesUrl = ossBean.getPostHost()+fileName;
        try {
            putObjectRequest = new PutObjectRequest(ossBean.getBucketName(),fileName, file.getInputStream());
            log.info("图片地址："+imagesUrl);
            return imagesUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            //关闭资源
            client.putObject(putObjectRequest);
            client.shutdown();
        }
    }


}
